const axios = require("axios");
axios.defaults.timeout = 40 * 1000;

let _ctx;
/**自动判断是在控制台打印还是阿里云的ctx */
const cLog = (...msg) => {
  const data = ["\n", ...msg, "\n"];
  if (_ctx) {
    _ctx.logger.info(...data);
    console.log(...data);
  } else {
    console.log(...data);
  }
};

/**处理要发送的内容 */
const handleContent = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const content = [];
      const { start, weather, daily, end, classTable, sentence } = require("./input");

      //根据不同的配置，增加不同的内容
      //开头语模块
      if (start.open) {
        content.push(`${start.content}`);
        cLog("开头语处理成功", start.content);
      }
      //课表模块
      if (classTable.open) {
        const handleClassTable = require("./functions/classTable");
        const classTableContent = await handleClassTable();
        content.push(`\n\n${classTableContent}`);
        cLog("课表处理成功", classTableContent);
      }
      // 天气模块
      if (weather.open) {
        const handleWeather = require("./functions/weather");
        const weatherContent = await handleWeather();
        content.push(`\n\n${weatherContent}`);
        cLog("天气处理成功", weatherContent);
      }
      //纪念日模块
      if (daily.open) {
        const handleTimeList = require("./functions/daily");
        const dailyContent = await handleTimeList();
        content.push(`\n\n${dailyContent}`);
        cLog("纪念日处理成功", dailyContent);
      }
      //结束模块
      if (end.open) {
        content.push(`\n\n${end.content}`);
        cLog("结束语处理成功");
      }
      //彩虹屁
      if (sentence.open) {
        const res = await axios.get("https://api.shadiao.pro/chp");
        content.push(`\n\n💘${res.data.data.text}`);
        cLog("彩虹屁处理成功", res.data.data.text);
      }
      //如果啥都没输入的话
      if (content.length === 0) {
        content.push("请最少配置一个模块内容,没有内容无法推送");
      }
      resolve(content.join("")); //转字符串
    } catch (error) {
      cLog("处理内容失败", error.message || error);
      reject(error.message || error);
    }
  });
};
//真正用于阿里云函数的东西：
module.exports = push = async (ctx) => {
  try {
    _ctx = ctx;
    const { getNowDay } = require("./functions/utils");
    cLog("__当前时间为__", getNowDay(_ctx));
    const content = await handleContent(ctx);
    const robot = require("./functions/robotPush");
    const res = await robot(content);
    return JSON.stringify({ success: true, data: res });
  } catch (error) {
    return JSON.stringify({ success: false, errMsg: error.message || error });
  }
};

//#region ——————本地测试部分
const express = require("express");
const app = express();
app.listen(8090, () => {
  console.log("\n测试环境开启于 http://localhost:8090 \n");
});
app.get("/", async (req, res) => {
  const pushRes = await push();
  res.send(pushRes);
});
//#endregion
